﻿using AutoMapper;
using MediatR;
using Mysqlx.Crud;
using MySqlX.XDevAPI.Common;
using Return.Enum;
using SlaughterItem.Common.Infrastructures.Interfaces;
using THE_WIND_RISES.Common.Domans.RBAC;

namespace RBAC_Set.API.Application.Commands
{
    public class AddRoleHandler : IRequestHandler<AddRoleCommand, THE_WIND_RISES.Common.Dtos.Result>
    {
        public IBaseRepository<Role> RoleRep { get; set; }
        public IBaseRepository<RolePerm> RolePermRep { get; set; }
        public IMapper mapper { get; set; }
        public ILogger<AddRoleHandler> logger;

        public AddRoleHandler(IBaseRepository<Role> roleRep, IMapper mapper, IBaseRepository<RolePerm> rolePermRep, ILogger<AddRoleHandler> logger)
        {
            RoleRep = roleRep;
            this.mapper = mapper;
            RolePermRep = rolePermRep;
            this.logger = logger;
        }

        /// <summary>
        /// 添加角色信息  及其  角色权限关联信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<THE_WIND_RISES.Common.Dtos.Result> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
            var result = new THE_WIND_RISES.Common.Dtos.Result() { Code = (int)CommonErrorCodes.Added };
            try
            {
                var AddNum = 0;
                string RoleShowSql = $"select * from Role where RoleName = '{request.RoleName}' ";

                var Roleres = RoleRep.GetAll(RoleShowSql).FirstOrDefault();
                if (Roleres == null)
                {
                    logger.LogInformation("添加角色信息");
                    var AddData = mapper.Map<Role>(request);
                    string sql = "insert into Role values(@RoleId,@RoleCoding,@RoleName,@RoleState,@IsDelete,@Handle,@HandleContext,@HandleTime,@Pid);";
                    AddNum = RoleRep.Add(sql, AddData);
                    string RoleShowSql1 = $"select * from Role where RoleName = '{request.RoleName}' ";
                    Roleres = RoleRep.GetAll(RoleShowSql1).FirstOrDefault();
                }
                string RolePermShowSql = $"select * from RolePerm where RoleId = {Roleres.RoleId} and PermissionId = {request.PermissionId}";
                var ShowRolePermres = RolePermRep.GetAll(RolePermShowSql).FirstOrDefault();
                if (ShowRolePermres == null)
                {
                    logger.LogInformation("角色权限关联信息为空，进行添加");
                    string RolePermAddSql = "insert into RolePerm values(@RolePermId,@RoleId,@PermissionId,@IsDelete);";
                    var AddRolePermres = RolePermRep.Add(RolePermAddSql, new
                    {
                        RolePermId = 0,
                        RoleId = Roleres.RoleId,
                        PermissionId = request.PermissionId,
                        IsDelete = false
                    });
                    string RolePermShowSql1 = $"select * from RolePerm where RoleId = {Roleres.RoleId} and PermissionId = {request.PermissionId}";
                    ShowRolePermres = RolePermRep.GetAll(RolePermShowSql1).FirstOrDefault();
                }
                if (Roleres != null && ShowRolePermres != null)
                {
                    AddNum += 1;
                }
                else
                {
                    result.Code = (int)CommonErrorCodes.Added;
                    result.Data = null;
                    result.Msg = "添加失败，角色名称或权限信息重复";
                    logger.LogError("添加失败，角色名称或权限信息重复");
                    return result;
                }
                if (AddNum == 2)
                {
                    result.Code = (int)CommonErrorCodes.Success;
                    result.Data = null;
                    result.Msg = "添加成功";
                    logger.LogInformation("添加角色和角色权限关联信息成功");
                    return result;
                }
            }
            catch (Exception)
            {
                logger.LogError("添加失败，角色名称或权限信息重复");
                throw;
            }
            return result;
        }
    }
}
